package com.gxa.shop.servlet.account;

import com.alibaba.fastjson.JSON;
import com.gxa.shop.bean.pojo.Account;
import com.gxa.shop.commons.r.R;
import com.gxa.shop.bean.dto.Login;
import com.gxa.shop.service.account.LoginService;
import com.gxa.shop.service.account.impl.LoginServiceImpl;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

import java.util.stream.Collectors;

@WebServlet(name = "AdminLogin",value = "/account/login")
public class AccountLogin extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BufferedReader bufferedReader=req.getReader();
        String data="";
        // 接收数据
        data=bufferedReader.lines().collect(Collectors.joining());
        // 得到前端传递的账号和密码
        Login login= JSON.parseObject(data,Login.class);
        // 调用service层
        LoginService adminLogin=new LoginServiceImpl();
        Account account=adminLogin.login(login);
        R r=null;
        if (account!=null){
            System.out.println("数据库中存在当前用户");
            // 设置token的值
            String token =req.getSession().getId();
            r= R.ok("有该用户").addData("token",token).addData("account",account);
            getServletContext().setAttribute(token,account);
            req.getSession().setAttribute("admin",account);
        }else {
            System.out.println("用户名或者密码错误");
           r=R.error("用户名或者密码错误");
        }
        String jsonResult=JSON.toJSONString(r);
        PrintWriter writer=resp.getWriter();
        writer.write(jsonResult);
        writer.flush();
        writer.close();
    }
}
